package byj.com.meishi;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.SparseArray;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.Toast;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import byj.com.meishi.adapter.TabFindFragmentAdapter;
import byj.com.meishi.adapter.ToggleListViewAdapter;
import byj.com.meishi.bean.Title;
import byj.com.meishi.dao.ShouCangDao;
import byj.com.meishi.fragment.TitleFragment;
import byj.com.meishi.utils.AnalysisJson;
import byj.com.meishi.utils.OkHttpClientUtils;
import cn.bmob.v3.Bmob;

public class MainActivity extends AppCompatActivity {

    private DrawerLayout drawLayout;
    private LinearLayout ll;
    private ViewPager vp_main;
    private TabLayout tab;
    private Toolbar toolBar;
    private List<String> titleList;
    private List<String> listViewtitle;
    private SparseArray<Fragment> fragments;
    private TabFindFragmentAdapter adapter;
    private ActionBarDrawerToggle toggle;
    private List<Integer> imgIds;
    private ListView listView;
    private List<String> titles1;
    private Handler mHandler=new Handler(){
        @Override
        public void handleMessage(Message msg) {
            if(msg.what==1){
                titles = (List<Title>) msg.obj;

                titles1=new ArrayList<>();
                fragments = new SparseArray<>();
                int count=1;
                for (int i = 0; i < titles.size(); i++) {
                    TitleFragment titleFragment = new TitleFragment();
                    String itemPath = PinJiePath(Constant.VIDEO_LIST, titles.get(i).getId(), "14");
                    titles1.add(titles.get(i).getTitle());
                    titleFragment.setPath(itemPath,count);
                    fragments.put(i,titleFragment);
                }
                //创建适配器
                adapter = new TabFindFragmentAdapter(getSupportFragmentManager(),fragments,titles1);
                vp_main.setAdapter(adapter);
                tab.setupWithViewPager(vp_main);
            }
        }
    };
    private List<Title> titles;
    private ToggleListViewAdapter adapter1;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        supportRequestWindowFeature(Window.FEATURE_NO_TITLE);
        setContentView(R.layout.activity_main);
        //第一：默认初始化
       Bmob.initialize(this, "8313918049043c372eaaf197c3ee6956");

        //找到组件
        initView();
        //为toolBar设置属性
        setViewParams();

    }

    private void downloadBaseTitleJson(){
        final String path = PinJiePath(Constant.CATEGOTY_URL, "", "");
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    String categoryJson = OkHttpClientUtils.getStringFromUrl(path);
                    List<Title>titles = AnalysisJson.analysisJsonData(categoryJson);
                    Message obtain = Message.obtain();
                    obtain.what=1;
                    obtain.obj=titles;
                    mHandler.sendMessage(obtain);

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();


    }
    private String PinJiePath(String path,String id,String count){
        path=Constant.BASE_URL+path;
        if(id.equals("")&&count.equals("")){
            return path;
        }else {
            path=path+"?";
            if(!id.equals("")&&path.endsWith("?")){
                path=path+"id="+id;
            }else if(!id.equals("")){
                path=path+"&&id="+id;
            }

            if(!count.equals("")&&count.endsWith("?")){
                path=path+"count="+count;
            }else if(!count.equals("")){
                path=path+"&&count="+count;
            }

            return path;

        }

    }

    private void setViewParams() {
        assert toolBar!=null;
        toolBar.setNavigationIcon(R.mipmap.ic_launcher);
        toolBar.setNavigationOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Toast.makeText(MainActivity.this,"被点击了。。。",Toast.LENGTH_SHORT).show();
            }
        });
        toolBar.setTitle("美视");
        //为TabLayout设置属性
        downloadBaseTitleJson();
        //设置抽屉
        toggle = new ActionBarDrawerToggle(this, drawLayout, toolBar, R.string.drawer_open, R.string.drawer_close);
        //同步抽屉状态
        toggle.syncState();
        //添加监听
        drawLayout.addDrawerListener(toggle);
        //得到ListView适配器的数据源
        String[] listArray = getResources().getStringArray(R.array.listtitle_item);
        getListViewTitles(listArray);
        getImgIds();
        //为抽屉中ListView创建适配器
        adapter1 = new ToggleListViewAdapter(listViewtitle,imgIds);
        listView.setAdapter(adapter1);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                String s = (String) adapterView.getItemAtPosition(i);
                if (s.equals("收藏")){
                    Intent intent = new Intent(MainActivity.this,ShoucangActivity.class);
                    startActivity(intent);
                }else if(s.equals("清除下载")){
                    final ShouCangDao dao = new ShouCangDao(MainActivity.this);
                    dao.deleteBiao("delete from collect");
                }
            }
        });

    }
    //把ListView的图片id添加到集合中
    private void getImgIds(){
        imgIds = new ArrayList<>();
        int[] imgIdArray = getImgIdArray();
        for (int i = 0; i < imgIdArray.length; i++) {
            imgIds.add(imgIdArray[i]);
        }

    }
    //得到ListView中的图片
    private int[] getImgIdArray(){
        return new int[]{R.mipmap.ic_menu_camera,R.mipmap.ic_menu_gallery,
        R.mipmap.ic_menu_slideshow,R.mipmap.ic_menu_manage,
        R.mipmap.ic_menu_share,R.mipmap.ic_menu_send};
    }

    //得到抽屉中的ListView中的title
    private void getListViewTitles(String[] titles){
        listViewtitle = new ArrayList<>();
        for (int i = 0; i < titles.length; i++) {
            listViewtitle.add(titles[i]);
        }

    }
//得到组件
    private void initView() {
        drawLayout = (DrawerLayout) findViewById(R.id.deaw_layout);
        toolBar = (Toolbar) findViewById(R.id.toolbar);
        tab = (TabLayout) findViewById(R.id.tab_layout);
        vp_main = (ViewPager) findViewById(R.id.vp_FindFragment_pager);
        ll = (LinearLayout) findViewById(R.id.ll_togglebar);
        listView = (ListView) findViewById(R.id.lv_toggle);
    }

    public void login(View view) {
        Intent intent = new Intent(MainActivity.this,LoginActivity.class);
        startActivity(intent);
    }

    public void register(View view) {
        Intent intent = new Intent(MainActivity.this,RegisterActivity.class);
        startActivity(intent);
    }
}
